package org.geekbang.prepare.lesson1.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;

public class MyServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doGet Method !");
        req.setAttribute("forward","yes");
        String forwardType = req.getParameter("forwardType");
        if ("jsp".equals(forwardType)) {
            req.getRequestDispatcher("/forward.jsp").forward(req,resp);
            return;
        }
        req.getRequestDispatcher("/forward").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("do post !");
        Enumeration<String> params = req.getHeaderNames();
        while (params.hasMoreElements()){
            String key = params.nextElement();
            System.out.printf("key : %s , values:%s \n",key, req.getHeader(key));
        }
        try(BufferedReader reader = req.getReader()){
            reader.lines().forEach(System.out::println);
        }

        resp.getWriter().println("hello ,post !");
    }
}
